

from jinja2 import Environment, FileSystemLoader
from urllib import parse
from setting import BASE_DIR, TEMPLATES, STATICFILES_DIRS
import os

from WebFrame.utils import Session, hash, getRandom

# import multipart#上传数据处理
import cgi


def listdir(path, list_name):  # 传入存储的list
    for file in os.listdir(path):
        file_path = os.path.join(path, file)
        if os.path.isdir(file_path):
            listdir(file_path, list_name)
        else:
            list_name.append(file_path)


class Application:
    def __init__(self) -> None:
        self.urls = {}

    def route(self, path=None):
        def wrapper(func):
            self.urls[path] = func
            return func
        return wrapper

    def __call__(self, environ, start_response):
        path = environ['PATH_INFO']
        if not environ.get('HTTP_COOKIE', None):
            environ['HTTP_COOKIE'] = hash(getRandom())
        self.form = self.post_data(environ)
        self.args = self.get_data(environ)
        if path in self.urls:
            res_body = self.urls[path](environ)
            if type(res_body) == type(''):
                status = '200 OK'
                response_headers = [
                    ('Content-Type', 'text/html; charset=utf-8')]
                start_response(status, response_headers)

                return [res_body.encode("utf-8")]
            else:
                status = res_body[1]
                response_headers = [
                    ('Content-Type', 'text/html; charset=utf-8'), ('Location', res_body[0])]
                start_response(status, response_headers)
                return [res_body[2].encode("utf-8")]

        static_dir = STATICFILES_DIRS
        res_path = os.path.join(static_dir, path[1:])
        if res_path.endswith('.png'):
            status = '200 OK'
            response_headers = [('content-type', 'image/png')]
            start_response(status, response_headers)

            with open(res_path, 'rb') as f:
                res_body = f.read()
            return [res_body]
        elif res_path.endswith('.jpg'):
            status = '200 OK'
            response_headers = [('content-type', 'image/jpg')]
            start_response(status, response_headers)

            with open(res_path, 'rb') as f:
                res_body = f.read()
            return [res_body]
        elif res_path.endswith('.gif'):
            status = '200 OK'
            response_headers = [('content-type', 'image/gif')]
            start_response(status, response_headers)

            with open(res_path, 'rb') as f:
                res_body = f.read()
            return [res_body]
        
        elif res_path.endswith('.css'):
            status = '200 OK'
            response_headers = [('Content-Type', 'text/css; charset=utf-8')]
            start_response(status, response_headers)

            with open(res_path, 'rb') as f:
                res_body = f.read()
            return [res_body]
        elif res_path.endswith('.js'):
            status = '200 OK'
            response_headers = [('Content-Type', 'text/script; charset=utf-8')]
            start_response(status, response_headers)

            with open(res_path, 'rb') as f:
                res_body = f.read()
            return [res_body]
        else:
            status = '404 Not Found'
            response_headers = [('Content-Type', 'text/html; charset=utf-8')]
            start_response(status, response_headers)
            erro_res_body = self.urls['/error/'](environ)
            return [erro_res_body.encode('utf-8')]

    def post_data(self, request):
        # res_data = {}
        d = cgi.FieldStorage(
            environ=request, fp=request['wsgi.input'], keep_blank_values=True)

        # forms, files=multipart.parse_form_data(request)
        # for k, v in forms.dict.items():
        #     res_data[k] = v[0] if v else None
        # res_data.update(files.dict)
        return d

    def get_data(self, request):
        res_data = {}
        data_dict = parse.parse_qs(request['QUERY_STRING'])
        for k, v in data_dict.items():
            res_data[k] = v[0] if v[0] else None
        return res_data

    def set_session(self, request, data):
        cookies = request['HTTP_COOKIE']
        key = hash(cookies)
        session = Session(key)
        session.update(data)

    def get_session(self, request):
        cookies = request['HTTP_COOKIE']
        key = hash(cookies)
        session = Session(key)
        now_session = session.get()

        return {'session': now_session}

    def render(self, request, html: str, context={}):
        # 集成jinja2模板系统
        session = self.get_session(request)

        context.update(session)
        template_dir = TEMPLATES['DIRS']
        env = Environment(loader=FileSystemLoader(str(template_dir)))
        template = env.get_template(html)
        return template.render(**context)


app = Application()


@app.route('/error/')
def error(request):
    return '''<div class="container">
    <p style="text-align: center;font-size: 50px;margin:100px">出错了</p>
</div>'''


def redirect(location, code='302 Found', Response=None):

    response = [location, code,
                '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
                '<title>Redirecting...</title>\n'
                '<h1>Redirecting...</h1>\n'
                '<p>You should be redirected automatically to target URL: '
                '<a href="%s">%s</a>.  If not click the link.' %
                (location, location)]
    return response
